package com.shop.config;

import com.shop.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableGlobalMethodSecurity(prePostEnabled = true)//开启security注解
@Configuration
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    MyUserDetailsService myUserDetailsService;
    @Autowired
    FuryAuthFailureHandler furyAuthFailureHandler;
    @Autowired
    FuryAuthSuccessHandler furyAuthSuccessHandler;

    @Autowired
    RestAuthAccessDeniedHandler restAuthAccessDeniedHandler;

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("-------------------->" + myUserDetailsService);
        auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder());

    }

    //http请求配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable()//禁用了 csrf 功能
//                .authorizeRequests()//限定签名成功的请求
//               // .antMatchers("/add").hasAnyRole("ADMIN")//对decision和govern 下的接口 需要 USER 或者 ADMIN 权限
//                .antMatchers("/add").permitAll()//对decision和govern 下的接口 需要 USER 或者 ADMIN 权限
//                .antMatchers("/login").permitAll() //  /login 不限定
//                .antMatchers().permitAll()
//                .and().anonymous()//对于没有配置权限的其他请求允许匿名访问
//                .and().formLogin() //使用 spring security 默认登录页面
//                .and().httpBasic();//启用http 基础验证
//配置没有权限的自定义处理类
        http.csrf().disable().authorizeRequests()
                .antMatchers("/admin/login").permitAll()
                .antMatchers("/add").hasRole("admins")
                .and().formLogin().loginProcessingUrl("/admin/login").failureHandler(furyAuthFailureHandler)
                .successHandler(furyAuthSuccessHandler)
                .and().exceptionHandling().accessDeniedHandler(restAuthAccessDeniedHandler);


    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetails() {
        return new MyUserDetailsService();
    }

}
